package com.xm.rsi.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xm.rsi.annotation.AuthCheck;
import com.xm.rsi.common.*;
import com.xm.rsi.constant.UserConstant;
import com.xm.rsi.exception.BusinessException;
import com.xm.rsi.exception.ThrowUtils;
import com.xm.rsi.model.dto.user.UserLoginRequest;
import com.xm.rsi.model.dto.user.UserQueryRequest;
import com.xm.rsi.model.dto.user.UserRegisterRequest;
import com.xm.rsi.model.dto.user.UserUpdateRequest;
import com.xm.rsi.model.entity.User;
import com.xm.rsi.model.vo.LoginUserVO;
import com.xm.rsi.model.vo.UserVO;
import com.xm.rsi.service.UserService;
import com.xm.rsi.utils.EmailUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/user")
public class UserController {
    
    @Resource
    private UserService userService;
    
    @Resource
    private EmailUtils emailUtils;

    /**
     * 发送邮箱
     * @param email
     * @return
     */
    @PostMapping("/sendEmail")
    public BaseResponse<String> sendEmail(@RequestParam String email) {
        if (email.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "邮箱不能为空！");
        }
        emailUtils.sendEmail(email, null);
        return ResultUtils.success("发送邮件成功！");
    }

    /**
     * 用户注册
     * @param userRegisterRequest
     * @return
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userEmail = userRegisterRequest.getUserEmail();
        String emailCode = userRegisterRequest.getEmailCode();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String userName = userRegisterRequest.getUserName();
        if (StringUtils.isAnyBlank(userEmail, userPassword, checkPassword, userName, emailCode)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请检查注册信息");
        }
        return ResultUtils.success(userService.userRegister(userEmail, userPassword, checkPassword, userName, emailCode));
    }

    /**
     * 更新用户
     * @param userUpdateRequest
     * @return
     */
    @PostMapping("/userUpdate")
    public BaseResponse<Boolean> userUpdate(@RequestBody UserUpdateRequest userUpdateRequest, HttpServletRequest request) {
        if (userUpdateRequest == null || userUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        if (!userService.isAdmin(user) && !userService.isRootAdmin(user) && !user.getId().equals(userUpdateRequest.getId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        String userEmail = userUpdateRequest.getUserEmail();
        String userPassword = userUpdateRequest.getUserPassword();
        String checkPassword = userUpdateRequest.getCheckPassword();
        String userName = userUpdateRequest.getUserName();
        Integer userState = Integer.parseInt(userUpdateRequest.getUserState());
        String userRole = userUpdateRequest.getUserRole();
        return ResultUtils.success(userService.userUpdate(userEmail, userPassword, checkPassword, userName, userState, userRole));
    }

    /**
     * 添加用户
     * @param userRegisterRequest
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addUser(@RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userEmail = userRegisterRequest.getUserEmail();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String userName = userRegisterRequest.getUserName();
        if (StringUtils.isAnyBlank(userEmail, userPassword, checkPassword, userName)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请检查用户信息");
        }
        return ResultUtils.success(userService.addOne(userEmail, userPassword, checkPassword, userName));
    }

    /**
     * 删除用户
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> delUser(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long id = deleteRequest.getId();
        User delUser = userService.getById(id);
        ThrowUtils.throwIf(delUser == null, ErrorCode.NOT_FOUND_ERROR);
        User user = userService.getLoginUser(request);
        if (!userService.isAdmin(user) && !userService.isRootAdmin(user)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        return ResultUtils.success(userService.removeById(id));
    }
    
    /**
     * 用户登录
     * @param userLoginRequest
     * @param request
     * @return
     */
    @PostMapping("/login")
    public BaseResponse<LoginUserVO> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request, HttpServletResponse response) {
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userEmail = userLoginRequest.getUserEmail();
        String userPassword = userLoginRequest.getUserPassword();
        boolean isRemember = userLoginRequest.isRemember();
        if (StringUtils.isAnyBlank(userEmail, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        return ResultUtils.success(userService.userLogin(userEmail, userPassword, isRemember, request, response));
    }

    /**
     * 用户注销
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request, HttpServletResponse response) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = userService.userLogout(request, response);
        return ResultUtils.success(result);
    }

    /**
     * 修改密码
     * @param userRegisterRequest
     * @return
     */
    @PostMapping("/changePwd")
    public BaseResponse<String> changePwd(@RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userEmail = userRegisterRequest.getUserEmail();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String emailCode = userRegisterRequest.getEmailCode();
        if (StringUtils.isAnyBlank(userEmail, userPassword, checkPassword, emailCode)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请检查表单信息");
        }
        return ResultUtils.success(userService.changePwd(userEmail, userPassword, checkPassword, emailCode));
    }

    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @GetMapping("/get/login")
    public BaseResponse<LoginUserVO> getLoginUser(HttpServletRequest request) {
        User user = userService.getLoginUser(request);
        return ResultUtils.success(userService.getLoginUserVO(user));
    }

    /**
     * 获取用户列表
     * @param userQueryRequest
     * @return
     */
    @PostMapping("/userList")
    @AuthCheck(anyRole = {UserConstant.ADMIN_ROLE, UserConstant.ROOT_ROLE})
    public BaseResponse<Page<UserVO>> listUserVoByPage(@RequestBody UserQueryRequest userQueryRequest) {
        long current = userQueryRequest.getCurrent();
        long pageSize = userQueryRequest.getPageSize();
        String userName = userQueryRequest.getUserName();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userRole", "user");
        queryWrapper.like(StringUtils.isNoneBlank(userName), "userName", userName);
        queryWrapper.orderByDesc("createTime");
        return ResultUtils.success(userService.getUserVOPage(current, pageSize, queryWrapper));
    }

    /**
     * 获取管理员列表
     * @param userQueryRequest
     * @return
     */
    @PostMapping("/adminList")
    @AuthCheck(mustRole = UserConstant.ROOT_ROLE)
    public BaseResponse<Page<UserVO>> listAdminVoByPage(@RequestBody UserQueryRequest userQueryRequest) {
        long current = userQueryRequest.getCurrent();
        long pageSize = userQueryRequest.getPageSize();
        String userName = userQueryRequest.getUserName();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userRole", "admin");
        queryWrapper.like(StringUtils.isNoneBlank(userName), "userName", userName);
        queryWrapper.orderByDesc("createTime");
        return ResultUtils.success(userService.getUserVOPage(current, pageSize, queryWrapper));
    }

    /**
     * 根据id获取用户
     * @param userId
     * @return
     */
    @GetMapping("/get/id")
    @AuthCheck(anyRole = {UserConstant.ADMIN_ROLE, UserConstant.ROOT_ROLE})
    public BaseResponse<User> getById(Long userId, HttpServletRequest request) {
        User searchUser = userService.getLoginUser(request);
        User user = userService.getById(userId);
        if (userService.isRootAdmin(user) && userService.isAdmin(searchUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        return ResultUtils.success(user);
    }

    /**
     * 获取自己的用户信息
     * @param userId
     * @param request
     * @return
     */
    @GetMapping("/get/my")
    public BaseResponse<UserVO> getOwnById(Long userId, HttpServletRequest request) {
        User searchUser = userService.getLoginUser(request);
        User user = userService.getById(userId);
        if (!searchUser.getId().equals(userId)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        return ResultUtils.success(userService.getUserVO(user));
    }
}
